package com.dragon.user_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.user_service.Exception.BusinessException;
import com.dragon.user_service.Exception.StateCode;
import com.dragon.user_service.api.MQ.pushLogService;
import com.dragon.user_service.api.MQ.writeLogEvent;
import com.dragon.user_service.api.RPC.permissionService;
import com.dragon.user_service.domain.Enum.UserRoleEnum;
import com.dragon.user_service.domain.dto.request.user.UserLoginRequest;
import com.dragon.user_service.domain.dto.request.user.UserQueryRequest;
import com.dragon.user_service.domain.dto.request.user.UserRegisterRequest;
import com.dragon.user_service.domain.entity.User;
import com.dragon.user_service.domain.vo.user.LoginUserVO;
import com.dragon.user_service.domain.vo.user.UserVO;
import com.dragon.user_service.mapper.UserMapper;
import com.dragon.user_service.service.UserService;
import com.dragon.user_service.util.JwtUtils;
import com.dragon.user_service.util.ThrowUtil;

//import org.apache.seata.spring.annotation.GlobalTransactional;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;
import org.apache.shardingsphere.transaction.annotation.ShardingSphereTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
/**
 * @author 20390
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-01-21 10:08:38
 */
@Service
public class userServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;
    @Autowired
    private JwtUtils jwtUtils;
    @Resource
    private pushLogService pushLogService;
    @Resource
    private permissionService permissionService;

    @Override
//    @GlobalTransactional(timeoutMills = 300000, name = "spring-seata-tx")
    @ShardingSphereTransactionType(TransactionType.BASE) // 指定Seata AT模式
    @Transactional(rollbackFor = Exception.class) // Spring事务注解
    public boolean userRegister(UserRegisterRequest userRegisterRequest, HttpServletRequest request) {
        String userName = userRegisterRequest.getUserName();
        String password = userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        if (ObjectUtil.isEmpty(userName) || ObjectUtil.isEmpty(password) || ObjectUtil.isEmpty(checkPassword) || ObjectUtil.isEmpty(request)) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
//        如果密码长度小于8位，报错
        ThrowUtil.throwIf(password.length() < 8, StateCode.PARAMS_ERROR, "密码长度不能小于8位");

//        用户名检查:
//        ThrowUtil.throwIf(userName.length()<4,StateCode.PARAMS_ERROR,"账号长度不能小于4位");
//        如果两次密码输入不一致，报错
        ThrowUtil.throwIf(!StrUtil.equals(password, checkPassword), StateCode.PARAMS_ERROR, "两次密码输入不一致");

//        如果账号已经重复，报错
        String encryptPassword = getEncryptPassword(password);
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("userName", userName);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(StateCode.PARAMS_ERROR, "用户名已被占用，请更换用户名");
        }
        User user = new User();
        user.setUserPassword(encryptPassword);
        user.setUserName(userName);

        int count2 = userMapper.insert(user);
        ThrowUtil.throwIf(count2 != 1, StateCode.SYSTEM_ERROR, "用户注册失败，系统错误");

        Long userId = user.getUser_id();
//      用seata来实现分布式事务
        if(1==1){throw new NullPointerException();}
//      调用权限服务绑定角色(RPC调用)
        permissionService.bindDefaultRole(userId);

//      发送MQ:发送"Register"日志消息
        pushLogService.sendSaveLogMsg(
                                 writeLogEvent.builder()
                                .user_id(userId)
                                .action("用户注册,调用权限服务(RPC)绑定角色信息")
                                .ip("暂且未知")
                                .detail("user表新增一条记录,user_roles表新增一条记录")
                                .build());

        return true;
    }

    @Override
    public LoginUserVO userLogin(UserLoginRequest userLoginRequest, HttpServletResponse response) {
        String userName = userLoginRequest.getUserName();
        String password = userLoginRequest.getUserPassword();

        if (ObjectUtil.isEmpty(userName) || ObjectUtil.isEmpty(password)) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
//        如果密码长度小于8位，报错
        ThrowUtil.throwIf(password.length() < 8, StateCode.PARAMS_ERROR, "密码长度不能小于8位");
//        如果账号长度小于4位，报错
//        ThrowUtil.throwIf(userName.length()<4,StateCode.PARAMS_ERROR,"账号长度不能小于4位");
//        如果账号不存在，报错
        String encryptPassword = getEncryptPassword(password);
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("userName", userName);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(user)) {
            throw new BusinessException(StateCode.PARAMS_ERROR, "账号或密码错误");
        }
        // 3. 记录用户的登录态,使用JWT+TOKEN实现
        String token = jwtUtils.createToken(user);
        response.setHeader("Authorization", "Bearer " + token);

        LoginUserVO loginUserVO = getLoginUserVO(user);
        return loginUserVO;
    }

    public User getLoginUser(HttpServletRequest request) {
        ThrowUtil.throwIf(ObjectUtil.isEmpty(request), StateCode.PARAMS_ERROR);
        String authorizationHeader = request.getHeader("Authorization"); // 获取Authorization头
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String jwtToken = authorizationHeader.substring(7); // 提取Token字符串
            // ... 验证Token
            User loginUser = jwtUtils.getUserOrNull(jwtToken);
            if (ObjectUtil.isEmpty(loginUser)) {
                throw new BusinessException(StateCode.PARAMS_ERROR, "用户未登录");
            }
            return loginUser;
        } else {
            throw new BusinessException(StateCode.PARAMS_ERROR, "用户未登录");
        }
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (userList == null) {
            return new ArrayList<>();
        }
//        List<UserVO> arrayList=new ArrayList<>();
//        for (User user : userList) {
//            UserVO userVO=new UserVO();
//            BeanUtil.copyProperties(user,userVO);
//            arrayList.add(userVO);
//        }
        List<UserVO> userVOList = userList.stream().
                map(this::getUserVO).
                collect(Collectors.toList());
        return userVOList;
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        ThrowUtil.throwIf(ObjectUtil.isEmpty(request), StateCode.PARAMS_ERROR);
        String authorizationHeader = request.getHeader("Authorization"); // 获取Authorization头
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String jwtToken = authorizationHeader.substring(7); // 提取Token字符串
            // ... 验证Token
            User loginUser = jwtUtils.getUserOrNull(jwtToken);
            if (ObjectUtil.isEmpty(user)) {
                throw new BusinessException(StateCode.PARAMS_ERROR, "用户未登录");
            }
            //这里的可选方案有很多
            // 本地缓存(分布式场景不可用) 数据库表加一个字段(作为同一个用户所有token的表示),可以将该用户的所有token都失效
            //redis 存黑名单

            //总之这里是将token加入黑名单的操作,后续补坑
            //
        } else {
            throw new BusinessException(StateCode.PARAMS_ERROR, "用户未登录");
        }
        return true;
    }

    @Override
    public User getUserById(long id) {
        ThrowUtil.throwIf(id <= 0, StateCode.PARAMS_ERROR);
        User user = userMapper.selectById(id);
        ThrowUtil.throwIf(user == null, StateCode.NOT_FOUND_ERROR, "未找到该用户");
        return user;
    }

    @Override
    public UserVO getUserVOById(long id) {
        UserVO userVO = new UserVO();
        User userById = getUserById(id);
        BeanUtil.copyProperties(userById, userVO);
        return userVO;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(StateCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public String getEncryptPassword(String password) {
        final String salt = "dragon";
        return DigestUtils.md5DigestAsHex((password + salt).getBytes());
    }

}




